/**
 * Created by wengca on 2017/10/23 0023.
 */
var rp = require('request-promise');
var qs = require('querystring');
var path = require("path");
var fs = require('fs');
var dirPath = path.join(__dirname, "../orderfile");

class Request {
    constructor() {
    }
    /**
     * @param url
     * @param obj
     * @returns {Promise.<*>}
     * @constructor
     */
    async RequestPostFom(url, obj,headers) {
        try {
            let result = await  rp.post(url,{form:obj,headers,headers});
            return result
        }catch (err) {
            console.error(err);
            return {code: 500}
        }
    }

    async RequestPost(url, obj,headers) {
        try {
            let options = {
                method: 'POST',
                url: url,
                timeout: 3000,
                body: obj,
                headers: {
                    "content-type": "application/json",
                },
                json: true // Automatically stringifies the body to JSON
            };
            if (headers){
                options.headers = headers
            }
            let result = await  rp.post(options);
            return result
        }
        catch (err) {
            console.error(err);
            return {code: 500}
        }
    }
    /**
     * get获取到服务器信息
     * @param url
     * @param obj
     * @returns {Promise.<*>}
     * @constructor
     */
    async RequestGet(url,obj,headers) {
        try {
            url += qs.stringify(obj)
            console.log("url is",url)
            let options = {
                method: 'GET',
                url: url,
                timeout: 10000,
                body: JSON.stringify(obj),
                // headers: {
                //     "content-type": "application/json",
                // }
            };
            if (headers){
                options.headers = headers
            }
            let result = await rp.get(options);
            return result
        }
        catch (err) {
            console.log("RequestGet err", url, err);
            return {code: 500}
        }
    }

    async RequestDown(url,obj,headers) {
        try {
            url += qs.stringify(obj)
            console.log("url is", url)
            let options = {
                method: 'GEt',
                url: url,
                timeout: 3000,
                body: JSON.stringify(obj),
                headers: {
                    "content-type": "application/json",
                }
            };
            if (headers) {
                options.headers = headers
            }
            let stream = fs.createWriteStream(path.join(dirPath, "order.xls"));
            // console.log("stream",stream)
            let result = await rp.get(options).pipe(stream);
            return ({code: 200,result})
        }
        catch (err) {
            console.log("RequestGet err", url, err);
            return {code: 500}
        }
    }
}

module.exports = new Request();